TOOL.Category = "NPC Specifics"
TOOL.Name = "Combine Soldiers"
TOOL.Command = nil
TOOL.ConfigName = ""

local selectedCombine = {}

if CLIENT then
  language.Add( "Tool_npc_specific_soldier_name", "NPC Specifics: Combine Soldiers" )
  language.Add( "Tool_npc_specific_soldier_desc", "Select and tell soldiers to throw grenades" )
  language.Add( "Tool_npc_specific_soldier_0", "Left click to select a Soldier, Right-click to tell them to throw a grenade" )
end

local function npc_doNotify( message, symbol, user )
  if SERVER then
    user:SendLua("GAMEMODE:AddNotify(\"" .. message .. "\", " .. symbol .. ", \"5\"); surface.PlaySound( \"ambient/water/drip" .. math.random(1, 4) .. ".wav\" )")
  end
end

function TOOL:LeftClick( trace )
  if (trace.Hit && !trace.HitWorld && !trace.HitSky) then
    if (trace.Entity:IsValid()) then
      if (trace.Entity:IsNPC() && trace.Entity:GetClass() == "npc_combine_s") then
        if (selectedCombine[trace.Entity] == nil) then
          if SERVER then
            local speaknow = Sound("selected_combine.wav")
            trace.Entity:EmitSound( speaknow )
          end
          selectedCombine[trace.Entity] = trace.Entity
          npc_doNotify("NPC Selected", "NOTIFY_GENERIC", self:GetOwner())
        else
          selectedCombine[trace.Entity] = nil
          npc_doNotify("NPC un-selected", "NOTIFY_GENERIC", self:GetOwner())
        end
        return true
      end
    end
  end
end

function TOOL:RightClick( trace )
  local throwat = ""
  local lastname = ""
  if (trace.Hit && !trace.HitSky) then
    throwat = self:GetOwner():GetName() .. "_throwhere"
    if (SERVER || SinglePlayer()) then
      local deleteme = ents.FindByName(throwat)
      for k, v in pairs(deleteme) do
        if v:IsValid() then v:Remove() end
        local npc_newtarget = nil
        MsgAll("Deleted an old target\n")
      end
      
      npc_newtarget = ents.Create("info_target")
      MsgAll("Created a new target\n")
      npc_newtarget:SetPos(trace.HitPos)
      MsgAll("New pos = " .. tostring(trace.HitPos) .. "\n")
      npc_newtarget:Spawn()
      MsgAll("Spawned\n")
      npc_newtarget:SetName(throwat)
      MsgAll("Name changed to " .. throwat .. "\n")
    end
  end
  for i, v in pairs(selectedCombine) do
    //Make sure it hasn't been un-selected
    local NPC = v
    if (SERVER || SinglePlayer()) then
      if NPC:IsValid() then NPC:Fire("ThrowGrenadeAtTarget", throwat, 0) end
      MsgAll("Throwing grenade triggered\n")
    end
  end
  return true
end
